package com.mall.project.info.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mall.common.core.asserts.ApiAssert;
import com.mall.common.core.enums.ErrorCodeEnum;
import com.mall.common.security.utils.ApiUtils;
import com.mall.common.security.utils.AuthFile;
import com.mall.project.info.mapper.PhotoMapper;
import com.mall.project.info.model.entity.Photo;
import com.mall.project.info.service.IPhotoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 图片表 服务实现类
 * </p>
 *
 * @author Sam
 * @since 2022-01-04
 */
@Service
public class PhotoServiceImpl extends ServiceImpl<PhotoMapper, Photo> implements IPhotoService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Value("${custom.restPath}")
    private String restPath;

    @Value("${custom.photoServer}")
    private String photoServer;

    @Autowired
    private RestTemplate restTemplate;

    @Override
    public void deletePhoto(String photoBucket, String photoUrl) {
        // 静态创建域名数组
        photoUrl = photoUrl.replaceAll(photoServer, "");
        String uri = restPath + "/common/delete";
        String token = AuthFile.generateBucket(AuthFile.CustomAccessKey, AuthFile.CustomSecretKey, photoBucket);
        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        map.set("resource", photoUrl);
        map.set("token", token);
        uri = !map.isEmpty() ? UriComponentsBuilder.fromUriString(uri).queryParams(map).toUriString() : uri;
        try {
            restTemplate.delete(uri);
        } catch (RestClientException e) {
            logger.error("图片删除失败 bucket = " + photoBucket + " url = " + photoUrl, e);
            ApiAssert.failure(ErrorCodeEnum.INTERNAL_SERVER_ERROR.convert("删除失败"));
        }
    }

    @Override
    public void savePhoto(String tableId, String tableType, String randomNum) {
        //不执行图片
        if (StringUtils.isEmpty(randomNum) || StringUtils.isEmpty(tableType)) {
            return;
        }
        List<Photo> list = list(new LambdaQueryWrapper<Photo>().eq(Photo::getRandom, randomNum)
                .eq(Photo::getStatus, "临时").eq(Photo::getTableType, tableType));
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        LambdaUpdateWrapper<Photo> wrapper = Wrappers.<Photo>lambdaUpdate()
                .eq(Photo::getRandom, randomNum)
                .eq(Photo::getTableType, tableType)
                .set(Photo::getTableId, tableId)
                .set(Photo::getUserId, ApiUtils.currentUid())
                .set(Photo::getStatus, "正常")
                .set(Photo::getRandom, null);
        ApiAssert.isTrue(ErrorCodeEnum.INTERNAL_SERVER_ERROR.convert("保存图片失败"), update(wrapper));
    }

    @Override
    public List<String> listPhoto(String tableId, String tableType) {
        return this.list(Wrappers.<Photo>lambdaQuery()
                .select(Photo::getUrl)
                .eq(Photo::getTableId, tableId)
                .eq(Photo::getTableType, tableType))
                .stream().map(Photo::getUrl)
                .collect(Collectors.toList());
    }

}
